using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace WebApp8.Client.Services
{
    public class WeatherForecast
    {
        public DateOnly Date { get; set; }
        public int TemperatureC { get; set; }
        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
        public string? Summary { get; set; }
    }

    public class ApiService
    {
        private readonly ServiceDiscovery _serviceDiscovery;
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;

        public ApiService()
        {
            _serviceDiscovery = new ServiceDiscovery();
            _httpClient = new HttpClient();
            _jsonOptions = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            };
        }

        public async Task<List<WeatherForecast>?> GetWeatherForecastAsync()
        {
            try
            {
                var serviceUrl = await _serviceDiscovery.GetServiceUrl("WebApp8");
                if (serviceUrl == null)
                    throw new Exception("Service not found");

                var response = await _httpClient.GetAsync(new Uri(serviceUrl, "WeatherForecast"));
                response.EnsureSuccessStatusCode();

                var content = await response.Content.ReadAsStringAsync();
                return JsonSerializer.Deserialize<List<WeatherForecast>>(content, _jsonOptions);
            }
            catch (Exception ex)
            {
                throw new Exception($"Error getting weather forecast: {ex.Message}", ex);
            }
        }
    }
} 